﻿// ***********************************************************************
// Assembly         : Admin.Framework.Core.Application
// Author           : xwltz
// Created          : 2019-05-25
//
// Last Modified By : xwltz
// Last Modified On : 2019-05-25
// ***********************************************************************
// <summary>
//  IOC扩展
// </summary>
// ***********************************************************************

using System.Reflection;
using Admin.Framework.Core.Repository;
using Admin.Framework.Core.Repository.Interface;
using Autofac;

namespace Admin.Framework.Core.Application
{
    public class AutofacExt : Autofac.Module
    {
        /// <summary>
        /// Autofac容器对象
        /// </summary>
        private static IContainer _container;

        /// <summary>
        /// 初始化autofac
        /// </summary>
        public static void InitAutofac()
        {
            var builder = new ContainerBuilder();

            //注册数据库基础操作和工作单元

            //注册app层
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());

            _container = builder.Build();
        }

        /// <summary>
        /// 从Autofac容器获取对象
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        public static TEntity GetContainer<TEntity>()
        {
            return _container.Resolve<TEntity>();
        }
    }

    public class AutofacModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            // The generic ILogger<TCategoryName> service was added to the ServiceCollection by ASP.NET Core.
            // It was then registered with Autofac using the Populate method. All of this starts
            // with the `UseServiceProviderFactory(new AutofacServiceProviderFactory())` that happens in Program and registers Autofac
            // as the service provider.
            // builder.Register(c => new ValuesService(c.Resolve<ILogger<ValuesService>>())).As<IValuesService>().InstancePerLifetimeScope();
            
            
            //注册数据库基础操作
            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IRepository<>)).PropertiesAutowired();

            //注册app层
            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly());

        }
    }
}
